<template>
  <div class="prize-manage">
    <div class="actions" style="display: flex; gap: 12px; align-items: center">
      <el-button type="primary" @click="openDialog">新增奖品</el-button>
      <el-select v-model="filterActivityId" clearable placeholder="按活动筛选" style="width: 240px">
        <el-option v-for="a in activityList" :key="a.id" :label="a.name" :value="a.id" />
      </el-select>
    </div>

    <div class="table-wrapper">
      <el-table :data="filteredPrizeList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="活动" width="160">
          <template #default="{ row }">{{ activityName(row.activityId) }}</template>
        </el-table-column>
        <el-table-column prop="level" label="奖项等级" width="120" />
        <el-table-column prop="name" label="奖品名称" />
        <el-table-column label="图片" width="120">
          <template #default="{ row }">
            <el-image
              v-if="row.image"
              :src="row.image"
              style="width: 80px; height: 50px"
              fit="cover"
              @click="openPreview(row.image)"
            />
            <span v-else class="text-gray">无</span>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="100" />
        <el-table-column prop="probability" label="概率(%)" width="120" />
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button size="small" @click="editPrize(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="removePrize(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="form.id ? '编辑奖品' : '新增奖品'"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="所属活动" required>
          <el-select v-model="form.activityId" placeholder="选择活动">
            <el-option v-for="a in activityList" :key="a.id" :label="a.name" :value="a.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="奖项等级" required>
          <el-select v-model="form.level">
            <el-option label="一等奖" value="一等奖" />
            <el-option label="二等奖" value="二等奖" />
            <el-option label="三等奖" value="三等奖" />
            <el-option label="安慰奖" value="安慰奖" />
          </el-select>
        </el-form-item>

        <el-form-item label="奖品名称" required>
          <el-input v-model="form.name" />
        </el-form-item>

        <el-form-item label="奖品图片">
          <el-upload
            class="upload-demo"
            action=""
            list-type="picture-card"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleUploadChange"
          >
            <div v-if="form.image">
              <img :src="form.image" style="width: 100%; height: 100%; object-fit: cover" />
            </div>
            <div v-else class="upload-placeholder">
              <el-icon><Plus /></el-icon>
              <div style="font-size: 12px">上传图片</div>
            </div>
          </el-upload>
        </el-form-item>

        <el-form-item label="数量" required>
          <el-input-number v-model="form.quantity" :min="0" />
        </el-form-item>

        <el-form-item label="中奖概率(%)" required>
          <el-input-number v-model="form.probability" :min="0" :max="100" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="savePrize">保存</el-button>
      </template>
    </el-dialog>

    <!-- 预览 -->
    <el-dialog v-model="previewVisible" width="600px">
      <img :src="previewImageUrl" style="width: 100%; height: auto" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="PrizeManage">
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { UploadFile } from 'element-plus'

import { getPrizeList, addPrize, updatePrize, deletePrize, type Prize } from '@/api/prize'
import { getActivityList, type Activity } from '@/api/activity'

/* data */
const prizeList = ref<Prize[]>([])
const activityList = ref<Activity[]>([])

/* UI */
const dialogVisible = ref(false)
const previewVisible = ref(false)
const previewImageUrl = ref('')
const route = useRoute()
const filterActivityId = ref<number | null>(null)

/* form */
const form = ref<Partial<Prize>>({
  id: 0,
  activityId: 0,
  level: '一等奖',
  name: '',
  quantity: 1,
  probability: 0,
  image: ''
})

/* load */
async function loadData(): Promise<void> {
  prizeList.value = await getPrizeList()
  activityList.value = await getActivityList()
}
onMounted(async () => {
  await loadData()
  const q = route.query.activityId
  if (q) {
    const val = Number(q)
    if (!Number.isNaN(val)) filterActivityId.value = val
  }
})

const filteredPrizeList = computed(() => {
  if (!filterActivityId.value) return prizeList.value
  return prizeList.value.filter(p => p.activityId === filterActivityId.value)
})

function activityName(id: number): string {
  return activityList.value.find(a => a.id === id)?.name ?? '未知活动'
}

/* preview */
function openPreview(url: string | undefined): void {
  if (!url) return
  previewImageUrl.value = url
  previewVisible.value = true
}

/* new/edit/delete */
function openDialog(): void {
  form.value = {
    id: 0,
    activityId: activityList.value.length ? activityList.value[0].id : 0,
    level: '一等奖',
    name: '',
    quantity: 1,
    probability: 0,
    image: ''
  }
  dialogVisible.value = true
}

function editPrize(row: Prize): void {
  form.value = { ...row }
  dialogVisible.value = true
}

async function removePrize(id: number): Promise<void> {
  try {
    await ElMessageBox.confirm('确认删除该奖品？', '删除确认', { type: 'warning' })
    await deletePrize(id)
    ElMessage.success('删除成功')
    await loadData()
  } catch (err) {
    console.error(err)
  }
}

/* upload */
function handleUploadChange(file: UploadFile): void {
  const raw = file.raw as File | undefined
  if (!raw) return
  const reader = new FileReader()
  reader.onload = e => {
    form.value.image = e.target?.result as string
  }
  reader.readAsDataURL(raw)
}

/* save */
async function savePrize(): Promise<void> {
  if (!form.value.activityId) {
    ElMessage.error('请选择所属活动')
    return
  }
  if (!form.value.name) {
    ElMessage.error('请输入奖品名称')
    return
  }
  if (form.value.probability === undefined || form.value.probability === null) {
    ElMessage.error('请输入概率')
    return
  }

  try {
    if (form.value.id) {
      await updatePrize(form.value as Prize)
    } else {
      await addPrize({
        activityId: Number(form.value.activityId),
        level: form.value.level || '奖项',
        name: form.value.name || '',
        quantity: Number(form.value.quantity) || 0,
        probability: Number(form.value.probability) || 0,
        image: form.value.image || ''
      })
    }
    ElMessage.success('保存成功')
    dialogVisible.value = false
    await loadData()
  } catch (err) {
    console.error(err)
    ElMessage.error('保存失败')
  }
}

/* reset */
function resetForm(): void {
  form.value = {
    id: 0,
    activityId: 0,
    level: '一等奖',
    name: '',
    quantity: 1,
    probability: 0,
    image: ''
  }
}
</script>

<style scoped>
.table-wrapper {
  padding: 12px 16px;
  background: #fff;
  border-radius: 8px;
  overflow-x: auto; /* 保持表格横向滚动可用 */
}
.prize-manage {
  padding: 16px;
}
.actions {
  margin-bottom: 16px;
}
.text-gray {
  color: #888;
}
.upload-placeholder {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #999;
}
</style>
